import Vue from 'vue';
import store from '@/store';
import lodash from 'lodash';
import vueTheme from 'theme-vue';
import VueRouter from 'vue-router';
import frontRoute from './front/index';
import adminRoute from './admin/index';
import staticRoute from './staticRoute';
import setHoverColor from '@/utils/colorUtils';
const VueRouterPush = VueRouter.prototype.push;
const VueRouterReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return VueRouterPush.call(this, location, onResolve, onReject);
	return VueRouterPush.call(this, location).catch(err => err);
}
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return VueRouterReplace.call(this, location, onResolve, onReject);
	return VueRouterReplace.call(this, location).catch(err => err);
}
Vue.use(VueRouter);
let Theme = new vueTheme();
const router = new VueRouter({
	// mode: 'history', // 或 'hash'
	routes: [...staticRoute, ...frontRoute, ...adminRoute],
	scrollBehavior() {
		return { y: 0 };
	}
});
const formatRouter = (routes) => {
	return routes.map(route => {
		if (route.children) {
			route.children = formatRouter(route.children);
		}
		return route;
	})
};
const whiteList = staticRoute.map(n => n.name).filter(n => !!n);
router.beforeEach(async (to, from, next) => {
	let token = store.getters.token;
	let userInfo = store.getters.userInfo;
	let isLogin = !!token && !lodash.isEmpty(userInfo);
	if (to.matched.length === 0) next('/404');
	if (isLogin) {
		let menuArr = store.getters.menuData;
		to.name === 'Login' ? next(from.fullPath) : next();
	} else if (to.matched.some(n => n.name === 'Front')) {
		next();
	} else if (!whiteList.some(n => n === to.name)) {
		next('/login');
	} else {
		next();
	}
})
router.afterEach((to, from) => {
	let userInfo = store.getters.userInfo;
	if (to.matched.some(n => n.name === 'Front')) {
		Theme.changeTheme('#357c65');
	} else if (to.matched.some(n => n.name === 'Admin')) {
		let matched = to.matched || [];
		let nomatched = matched.filter((n) => n.name !== 'Admin');
		document.title = nomatched.map((n) => n.meta.title).join(' - ');
		Theme.changeTheme(userInfo?.skin);
		setHoverColor(userInfo?.skin, 25);
	} else {
		Theme.changeTheme('#930b0b');
	}
})
export default router